//
//  YAUserAcount.swift
//  KeepCliming
//
//  Created by 鱼龙之梦 on 15/9/2.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit

class YAUserAcount: NSObject {
    var access_token:String?//存储获取的令牌
    var expiresDate:NSDate?
    var expires_in:NSTimeInterval = 0{//存取生命周期，转换成可以识别的日期
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var uid:String?
    var name:String?
    var avatar_large:String?
    init(dict:[String:AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        //
    }
    //为了便于调试，自定义对象可以重写description
    override var description:String{
        let keys = ["access_token","expires_in","expiresDate","uid","name","avatar_large"]
        
        return "\(dictionaryWithValuesForKeys(keys))"
    }
    //定义归档接档的全局路径 转换成NSString 是为了更好的调用NSString的拼接方法
    static let accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    func saveUserAcount(){
        printLog("保存路径："+YAUserAcount.accountPath)
        //键值归档
        NSKeyedArchiver.archiveRootObject(self, toFile: YAUserAcount.accountPath)
    }
    class func loadUserAcount()->YAUserAcount? {
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? YAUserAcount
        //解档加载用户账户的时候，需要判断toke的有效期
        if let date = account?.expiresDate{
            if date.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return account
            }
        }
        return nil
    }
    //归档编码
    func encodeWithCoder(aCoder:NSCoder){
        aCoder.encodeObject(access_token,forKey:"access_token")
        aCoder.encodeObject(expiresDate,forKey:"expiresDate")
        aCoder.encodeObject(uid,forKey:"uid")
        aCoder.encodeObject(name,forKey:"name")
        aCoder.encodeObject(avatar_large,forKey:"avatar_large")
    }
    init?(coder aDecoder:NSCoder){
        access_token = aDecoder.decodeObjectForKey("access_token") as?String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as?NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as?String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as?String
    }
}
